package com.qzl.feiq.strategy;

import com.qzl.feiq.annotation.ReceiveType;
import org.reflections.Reflections;

import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 策略生产工厂
 */
public class ReceiveFactory {
    //我们将策略类存入HashMap里面
    private static Map<Integer, Receive> map = new ConcurrentHashMap<>();

    //根据command获取对应的策略类
    public static Receive getInvokeStrategy(Integer command){
        return map.get(command);
    }
    //将策略类放入map里面
    public static void register(Integer command,Receive receive){
        if (Objects.isNull(command) || Objects.isNull(receive)){
            return;
        }
        map.put(command,receive);
    }
    // 注册所有策略
    static {
        Reflections reflections = new Reflections("com.qzl.feiq.strategy.impl"); // 替换为你的策略实现类所在包
        Set<Class<? extends Receive>> receiveClasses = reflections.getSubTypesOf(Receive.class);

        for (Class<? extends Receive> clazz : receiveClasses) {
            if (clazz.isAnnotationPresent(ReceiveType.class)) {
                ReceiveType annotation = clazz.getAnnotation(ReceiveType.class);
                int command = annotation.command();
                try {
                    map.put(command, clazz.getDeclaredConstructor().newInstance());
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
